<template>
  <div v-if="cardData" class="go-items-list-card">
    <n-card hoverable size="small">
      <div class="list-content">
        <!-- 顶部按钮 -->
        <div class="list-content-top">
          <mac-os-control-btn
              class="top-btn"
              :hidden="['remove']"
              @close="deleteHanlde"
              @resize="resizeHandle"
          ></mac-os-control-btn>
        </div>
        <!-- 中间 -->
        <div class="list-content-img" @click="resizeHandle">
          <n-image
              object-fit="contain"
              height="180"
              preview-disabled
              :src="
              requireUrl('project/moke-20211219181327.png')
            "
              :alt="cardData.Title"
              :fallback-src="requireErrorImg()"
          ></n-image>
        </div>
      </div>
      <template #action>
        <div class="go-flex-items-center list-footer" justify="space-between">
          <n-text class="go-ellipsis-1 find-element-dy" :title="cardData.Title">
            {{ cardData.Id }} {{ cardData.Title || '' }}
          </n-text>
          <!-- 工具 -->
          <div class="go-flex-items-center list-footer-ri">
            <n-space>
              <n-text>
                <n-badge
                    class="go-animation-twinkle"
                    dot
                    :color="cardData.Released ? '#34c749' : '#fcbc40'"
                ></n-badge>
                {{
                  cardData.Released
                      ? t('project.release')
                      : t('project.unreleased')
                }}
              </n-text>

              <!--              编辑按钮-->
              <template v-for="item in fnBtnList" :key="item.key">
                <template v-if="item.key === 'select'">
                  <n-dropdown
                      trigger="hover"
                      placement="bottom"
                      :options="selectOptions"
                      :show-arrow="true"
                      @select="handleSelect"
                  >
                    <n-button size="small">
                      <template #icon>
                        <component :is="item.icon"></component>
                      </template>
                    </n-button>
                  </n-dropdown>
                </template>

                <n-tooltip v-else placement="bottom" trigger="hover">
                  <template #trigger>
                    <n-button size="small" @click="handleSelect(item.key)">
                      <template #icon>
                        <component :is="item.icon"></component>
                      </template>
                    </n-button>
                  </template>
                  <component :is="item.label"></component>
                </n-tooltip>
              </template>
            </n-space>
          </div>
          <!-- end -->
        </div>
      </template>
    </n-card>
    <!--    项目设置元素-->
    <n-modal
        v-model:show="showProjectSettingModal"
        preset="dialog"
        title="项目设置"
        positive-text="保存"
        negative-text="取消"
        @positive-click="submitCallback"
    >
      <n-input v-model:value="CurrentSelectCardData.Title" placeholder="项目名称">
      </n-input>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref, PropType} from 'vue'
import {useMessage} from 'naive-ui'
import {
  MessageError,
  MessageLoading,
  MessageSuccess,
  renderIcon,
  renderLang,
  requireErrorImg,
  setSessionStorage
} from '@/utils'
import {icon} from '@/plugins'
import {MacOsControlBtn} from '@/components/Tips/MacOsControlBtn'
import {Chartype, HttpResultType} from '../../index.d'
// @ts-ignore
import UserPageApi from "@/api/flow/UserPageApi.js";
import {StorageEnum} from "@/enums/storageEnum";
import router from "@/router";
import {PreviewEnum} from "@/enums/pageEnum";
// @ts-ignore
import Utils from "@/vue2-flow/src/utils/Common.js";
import {useChartEditStore} from "@/store/modules/chartEditStore/chartEditStore";
// import {CreateComponentType} from "@/packages";
import {getSessionStorageInfo} from "@/views/preview/utils";
import {Project} from "@/api/ProjectsApi";
import {AxiosResponse} from "axios";
import {UserComponent} from "@/api/UserComponentsApi";

const t = window['$t']
const {
  EllipsisHorizontalCircleSharpIcon,
  CopyIcon,
  TrashIcon,
  PencilIcon,
  BrowsersOutlineIcon,
  HammerIcon,
  SendIcon,
  SettingsSharpIcon,
} = icon.ionicons5

const emit = defineEmits(['delete', 'resize', 'edit', 'released','refreshProject'])
const message = useMessage()
const props = defineProps({
  cardData: Object as PropType<Chartype>
})
const showProjectSettingModal = ref(false)
const CurrentSelectCardData = ref<Chartype>()

/**
 * 更新项目名称等信息
 */
const submitCallback = () => {
  Project.Update(CurrentSelectCardData.value).then(res => {
    const mes = res.Code === 1 ? '更新成功' : '更新失败'
    message.success(mes)
  })
  // new UserPageApi().UpdateProject(CurrentSelectCardData.value, (res: any) => {
  //   console.log(res)
  //   const mes = res === 1 ? '更新成功' : '更新失败'
  //   message.success(mes)
  // })
}
// 处理url获取
const requireUrl = (name: string) => {
  return new URL(`../../../../../assets/images/${name}`, import.meta.url).href
}

const fnBtnList = reactive([
  {
    label: renderLang('global.r_edit'),
    key: 'edit',
    icon: renderIcon(HammerIcon)
  },
  {
    lable: renderLang('global.r_more'),
    key: 'select',
    icon: renderIcon(EllipsisHorizontalCircleSharpIcon)
  }
])

const selectOptions = ref([
  {
    label: renderLang('global.r_preview'),
    key: 'preview',
    icon: renderIcon(BrowsersOutlineIcon)
  },
  {
    label: props.cardData?.Released
        ? renderLang('global.r_unpublish')
        : renderLang('global.r_publish'),
    key: 'released',
    icon: renderIcon(SendIcon)
  },
  {
    label: renderLang('global.r_delete'),
    key: 'delete',
    icon: renderIcon(TrashIcon)
  },
  {
    label: renderLang('global.r_setting'),
    key: 'setting',
    icon: renderIcon(SettingsSharpIcon)
  },
  {
    label: renderLang('global.r_backup'),
    key: 'backup',
    icon: renderIcon(CopyIcon)
  }
])
const chartEditStore = useChartEditStore()

const handleSelect = (key: string) => {
  const {cardData} = props
  const id = cardData?.Id as any
  CurrentSelectCardData.value = cardData
  if (!id) {
    MessageError("找不到项目，项目id为空")
    return
  }
  const UPA = new UserPageApi()
  switch (key) {
    case 'delete':
      deleteHanlde()
      break
    case 'edit': // 编辑项目
      Project.Get(id).then((res) => {
        if (!res?.IsSuccess) {
          MessageError('项目异常，可能被删除');
          return
        }
        UserComponent.Gets(id).then(Components => {
          const SaveRes = setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, JSON.parse(Components.Data))
          if (!SaveRes) {
            return;
          }
          getSessionStorageInfo(id)
          editHandle()
        })
      });
      break
    case 'preview':
      Project.Get(id).then(res => {
        const proj = res.Data
        if (Utils.IsEmpty(proj)) {
          MessageError('项目异常，未找到项目');
          return
        }
        proj.Id = id + ''
        setSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST, JSON.parse(proj.Components))
        router.push({
          path: PreviewEnum.CHART_PREVIEW.replace(':id(.*)*', id),
        })
      })
      break
    case 'released':
      Project.ReleasedById<HttpResultType>(id).then((res) => {
        if (res?.Code === -1) {
          MessageError('项目异常，未找到项目');
          return
        }
        MessageSuccess('发布成功,等待加载');
        emit('released', cardData)
      });
      break
    case 'setting':
      showProjectSettingModal.value = true
      break
    case 'backup':
      Project.CopyProject(id).then(res => {
        if (!res.IsSuccess) {
          MessageError('项目异常，可能被删除');
          return
        }
        MessageSuccess('复制成功,等待加载...');
        emit('refreshProject')
      })
      break
  }
}

// 删除项目处理
const deleteHanlde = () => {
  emit('delete', props.cardData)
}

// 编辑处理
const editHandle = () => {
  emit('edit', props.cardData)
}

// 放大处理
const resizeHandle = () => {
  emit('resize', props.cardData)
}
</script>

<style lang="scss" scoped>
$contentHeight: 180px;
@include go('items-list-card') {
  position: relative;
  border-radius: $--border-radius-base;
  border: 1px solid rgba(0, 0, 0, 0);
  @extend .go-transition;
  &:hover {
    @include hover-border-color('hover-border-color');
  }
  .list-content {
    margin-top: 20px;
    margin-bottom: 5px;
    cursor: pointer;
    border-radius: $--border-radius-base;
    @include background-image('background-point');
    @extend .go-point-bg;

    &-top {
      position: absolute;
      top: 10px;
      left: 10px;
      height: 22px;
    }

    &-img {
      height: $contentHeight;
      @extend .go-flex-center;
      @extend .go-border-radius;
      @include deep() {
        img {
          @extend .go-border-radius;
        }
      }
    }
  }
  .list-footer {
    flex-wrap: nowrap;
    justify-content: space-between;
    line-height: 30px;

    &-ri {
      justify-content: flex-end;
      min-width: 180px;
    }
  }
}
</style>
